package cn.msi.questionnaire.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Entity;
import org.dom4j.Node;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;
import org.dom4j.io.SAXReader;

import cn.msi.project.domain.Index;

/**
 * 调查问卷模板XML处理
 * 
 * @author Administrator
 * 
 */
public class TemplateXMLUtils {

	/**
	 * 生成完整的XML
	 * 
	 * @param indexText
	 * @param questionText
	 * @return
	 */
	public static String createTemplate(String indexText, String[] questionText) {
		Document document = DocumentHelper.createDocument();
		Element rootElement = document.addElement("template");
		Entity indexElement = DocumentHelper.createEntity("template", indexText);
		rootElement.add(indexElement);
		Element questionsElement = DocumentHelper.createElement("questions");
		rootElement.add(questionsElement);
		if (questionText != null) {
			for (String nodes : questionText) {
				nodes = nodes.replaceAll("<input type='text'>", "@F@");
				Entity questionElement = DocumentHelper.createEntity("questions", nodes);
				questionsElement.add(questionElement);
			}
		}
		return document.asXML();
	}

	/**
	 * 根据指标生成问卷模板
	 * 
	 * @param indexs
	 * @return
	 */
	public static String createTemplate(List<Index> indexs) {
		Document document = createTemplateAsIndex(indexs);
		InputStream stylesheet = TemplateXMLUtils.class.getClassLoader().getResourceAsStream("cn/msi/questionnaire/util/templateStylesheet.xsl");
		try {
			document = xmlTransformHtml(document, stylesheet);
		} catch (TransformerException e) {
			e.printStackTrace();
		}
		return document.asXML();
	}

	/**
	 * 根据XML生成模板
	 * 
	 * @param xml
	 * @return
	 */
	public static String createTemplate(String xml) {
		SAXReader saxreader = new SAXReader();
		InputStream is;
		Document document = null;
		try {
			is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
			Document doc = saxreader.read(is);
			InputStream stylesheet = TemplateXMLUtils.class.getClassLoader().getResourceAsStream("cn/msi/questionnaire/util/templateStylesheet.xsl");
			document = xmlTransformHtml(doc, stylesheet);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
		return document.asXML();
	}

	/**
	 * 根据XML生成问卷
	 * 
	 * @param xml
	 * @return
	 */
	public static String createNaire(String xml) {
		SAXReader saxreader = new SAXReader();
		InputStream is;
		Document document = null;
		try {
			is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
			Document doc = saxreader.read(is);
			InputStream stylesheet = TemplateXMLUtils.class.getClassLoader().getResourceAsStream("cn/msi/questionnaire/util/naireStylesheet.xsl");
			document = xmlTransformHtml(doc, stylesheet);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
		return document.asXML();
	}

	/**
	 * 生成XML
	 * 
	 * @return
	 */
	public static Document createTemplateAsIndex(List<Index> indexs) {
		Document document = DocumentHelper.createDocument();
		Element indexsElement = document.addElement("template").addElement("indexs");
		// 加入指标项
		for (Index index : indexs) {
			Element indexElement = indexsElement.addElement("index");
			if (index.getParentId() != null) {
				indexElement.addAttribute("parent", String.valueOf(index.getParentId()));
			} else {
				indexElement.addAttribute("parent", "0");
			}
			indexElement.addElement("indexId").addText(String.valueOf(index.getIndexId()));
			indexElement.addElement("indexName").addText(index.getIndexName());
			indexElement.addElement("sources").addText(String.valueOf(index.getSources()));
		}
		return document;
	}

	/**
	 * xml转换成html
	 * 
	 * @param doc
	 * @param stylesheet
	 * @return
	 * @throws TransformerException
	 */
	public static Document xmlTransformHtml(Document doc, InputStream stylesheet) throws TransformerException {
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer transformer = factory.newTransformer(new StreamSource(stylesheet));
		DocumentSource ds = new DocumentSource(doc);
		DocumentResult result = new DocumentResult();
		transformer.transform(ds, result);
		Document document = result.getDocument();
		return document;
	}

	/**
	 * 通过前三次问卷生成问卷
	 * 
	 * @param content
	 * @param contents
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String mergeNaire(String content, List<String> contents) {
		SAXReader saxreader = new SAXReader();
		InputStream is;
		Document document = null;
		Document document_one = null;
		Document document_two = null;
		Document document_three = null;
		try {
			// 读取字符串
			is = new ByteArrayInputStream(content.getBytes("UTF-8"));
			document = saxreader.read(is);
			for (int i = 0; i < contents.size(); i++) {
				switch (i) {
				case 0:
					is = new ByteArrayInputStream(content.getBytes("UTF-8"));
					document_one = saxreader.read(is);
					break;
				case 1:
					is = new ByteArrayInputStream(content.getBytes("UTF-8"));
					document_two = saxreader.read(is);
					break;
				case 2:
					is = new ByteArrayInputStream(content.getBytes("UTF-8"));
					document_three = saxreader.read(is);
					break;
				}
			}
			List<Element> questionList = document.selectNodes("//template/questions/question");
			for (Element element : questionList) {
				// 元素的uuid在整个xml中UUID值是唯一的。
				String uuid = element.element("uuid").getTextTrim();
				Element items = element.addElement("items");
				if (document_one != null) {
					Node n = document_one.selectSingleNode("//template/questions/question[uuid='" + uuid + "']");
					if (n != null) {
						addItem(n, items);
					}
				}
				if (document_two != null) {
					Node n = document_two.selectSingleNode("//template/questions/question[uuid='" + uuid + "']");
					if (n != null) {
						addItem(n, items);
					}
				}
				if (document_three != null) {
					Node n = document_three.selectSingleNode("//template/questions/question[uuid='" + uuid + "']");
					if (n != null) {
						addItem(n, items);
					}
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return document.asXML();
	}

	/**
	 * 添加元素
	 * 
	 * @param oldElement
	 * @param newElement
	 */
	private static void addItem(Node oldElement, Element newElement) {
		Element e = (Element) oldElement;
		String text = "";
		String use = e.element("use") != null ? e.element("use").getText() : "N";
		if (use != null && use.equals("Y")) {
			text = "适用";
			String questionText = e.element("questionText") != null ? e.element("questionText").getText() : "";
			String source = e.element("source") != null ? e.element("source").getText() : "";
			//
			text += "," + questionText + "," + source;
		} else {
			text = "不适用";
		}
		newElement.addElement("item").addText(text);
	}
}
